{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Input and Output\n",
    "================\n",
    "\n",
    "In this section, we describe printing, which includes the use of the `print` function, the old-style `%` format specifiers  and the new style `{}` format specifiers.\n",
    "\n",
    "Printing to standard output (normally the screen)\n",
    "-------------------------------------------------\n",
    "\n",
    "The `print` function is the most commonly used command to print information to the “standard output device” which is normally the screen.\n",
    "\n",
    "There are two modes to use print.\n",
    "\n",
    "### Simple print\n",
    "\n",
    "The easiest way to use the print command is to list the variables to be printed, separated by comma. Here are a few examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "a = 10\n",
    "b = 'test text'\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test text\n"
     ]
    }
   ],
   "source": [
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10 test text\n"
     ]
    }
   ],
   "source": [
    "print(a, b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The answer is 10\n"
     ]
    }
   ],
   "source": [
    "print(\"The answer is\", a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The answer is 10 and the string contains test text\n"
     ]
    }
   ],
   "source": [
    "print(\"The answer is\", a, \"and the string contains\", b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The answer is 10 and the string reads test text\n"
     ]
    }
   ],
   "source": [
    "print(\"The answer is\", a, \"and the string reads\", b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python adds a space between every object that is being printed.\n",
    "\n",
    "Python prints a new line after every print call. To suppress that, use the `end=` parameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Printing in line one...still printing in line one.\n"
     ]
    }
   ],
   "source": [
    "print(\"Printing in line one\", end='')\n",
    "print(\"...still printing in line one.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Formatted printing\n",
    "\n",
    "The more sophisticated way of formatting output uses a syntax very similar to Matlab’s `fprintf` (and therefor also similar to C’s `printf`).\n",
    "\n",
    "The overall structure is that there is a string containing format specifiers, followed by a percentage sign and a tuple that contains the variables to be printed in place of the format specifiers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a = 10 b = 20\n"
     ]
    }
   ],
   "source": [
    "print(\"a = %d b = %d\" % (10,20))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A string can contain format identifiers (such as `%f` to format as a float, `%d` to format as an integer, and `%s` to format as a string):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pi =  3.14\n"
     ]
    }
   ],
   "source": [
    "from math import pi\n",
    "print(\"Pi = %5.2f\" % pi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pi =      3.142\n"
     ]
    }
   ],
   "source": [
    "print(\"Pi = %10.3f\" % pi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pi = 3.14159265\n"
     ]
    }
   ],
   "source": [
    "print(\"Pi = %10.8f\" % pi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pi = 3\n"
     ]
    }
   ],
   "source": [
    "print(\"Pi = %d\" % pi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The format specifier of type `%W.Df` means that a Float should be printed with a total Width of `W` characters and `D` digits behind the Decimal point. (This is identical to Matlab and C, for example.)\n",
    "\n",
    "To print more than one object, provide multiple format specifiers and list several objects in the tuple:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pi = 3.141593, 142*pi = 446.106157 and pi^2 = 9.869604.\n"
     ]
    }
   ],
   "source": [
    "print(\"Pi = %f, 142*pi = %f and pi^2 = %f.\" % (pi,142*pi,pi**2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the conversion of a format specifier and a tuple of variables into string does not rely on the `print` command:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pi = 3.141593'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import pi\n",
    "\"pi = %f\" % pi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This means that we can convert objects into strings whereever we need, and we can decide to print the strings later – there is no need to couple the formatting closely to the code that does the printing.\n",
    "\n",
    "Overview of commonly used format specifiers using the astronomical unit as an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'149597870700.000000'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "AU = 149597870700  # astronomical unit [m]\n",
    "\"%f\" % AU        # line 1 in table"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| specifier         |         style         |  Example output for AU|\n",
    "|:------------------|:---------------------:|----------------------:|\n",
    "| `%f` |     floating point    |  `149597870700.000000`|\n",
    "| `%e` |  exponential notation |         `1.495979e+11`|\n",
    "| `%g` |  shorter of %e or %f  |          `1.49598e+11`|\n",
    "| `%d` |        integer        |         `149597870700`|\n",
    "| `%s` |  `str()` |         `149597870700`|\n",
    "| `%r` | `repr()` |        `149597870700L`|\n",
    "\n",
    "### “str” and “\\_\\_str\\_\\_”\n",
    "\n",
    "All objects in Python should provide a method `__str__` which returns a nice string representation of the object. This method `a.__str__()` is called when we apply the `str` function to object `a`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.14'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 3.14\n",
    "a.__str__()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.14'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `str` function is extremely convenient as it allows us to print more complicated objects, such as"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"[3, 4.2, ['apple', 'banana'], (0, 1)]\""
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = [3, 4.2, ['apple', 'banana'], (0, 1)]\n",
    "str(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The way Python prints this is that it uses the `__str__` method of the list object. This will print the opening square bracket `[` and then call the `__str__` method of the first object, i.e. the integer 3. This will produce `3`. Then the list object’s `__str__` method prints the comma `,` and moves on to call the `__str__` method of the next element in the list (i.e. `4.2`) to print itself. This way any composite object can be represented as a string by asking the objects it holds to convert themselves to strings.\n",
    "\n",
    "The string method of object `x` is called implicitly, when we\n",
    "\n",
    "-   use the “%s” format specifier to print `x`\n",
    "\n",
    "-   pass the object `x` directly to the print command:\n",
    "\n",
    "<!-- -->"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 4.2, ['apple', 'banana'], (0, 1)]\n"
     ]
    }
   ],
   "source": [
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3, 4.2, ['apple', 'banana'], (0, 1)]\n"
     ]
    }
   ],
   "source": [
    "print(\"%s\" % b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### “repr” and “\\_\\_repr\\_\\_”\n",
    "\n",
    "A second function, `repr`, should convert a given object into a string presentation *so that this string can be used to re-created the object using the `eval` function*. The `repr` function will generally provide a more detailed string than `str`. Applying `repr` to the object `x` will attempt to call `x.__repr__()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.141592653589793'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import pi as a1\n",
    "str(a1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.141592653589793'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "repr(a1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.141592653589793"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "number_as_string = repr(a1)\n",
    "a2 = eval(number_as_string)  # evaluate string \n",
    "a2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a2-a1                      # -> repr is exact representation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a1-eval(repr(a1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a1-eval(str(a1))           # -> str has lost a few digits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can convert an object to its `str()` or `repr` presentation using the format specifiers ``%s and ``%r, respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.141592653589793'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "\"%s\" % math.pi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.141592653589793'"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"%r\" % math.pi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### New-style string formatting\n",
    "\n",
    "A new system of built-in formatting allows more flexibility for complex cases, at the cost of being a bit longer.\n",
    "\n",
    "Basic ideas in examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Peter needs 4 pints'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{} needs {} pints\".format('Peter', 4)     # insert values in order"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Peter needs 4 pints'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{0} needs {1} pints\".format('Peter', 4)   # index which element"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'4 needs Peter pints'"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{1} needs {0} pints\".format('Peter', 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Peter needs 4 pints'"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"{name} needs {number} pints\".format(    # reference element to\n",
    "    name='Peter',number=4)               # print by name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Pi is approximately 3.141593.'"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Pi is approximately {:f}.\".format(math.pi)     # can use old-style format options for float"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Pi is approximately 3.14.'"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Pi is approximately {:.2f}.\".format(math.pi)   # and precision"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Pi is approximately   3.14.'"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Pi is approximately {:6.2f}.\".format(math.pi)  # and width"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a powerful and elegant way of string formatting, which is gradually being used more.\n",
    "\n",
    "##### Further information\n",
    "\n",
    "-   Examples <http://docs.python.org/library/string.html#format-examples>\n",
    "\n",
    "-   [Python Enhancement Proposal 3101](http://www.python.org/dev/peps/pep-3101/)\n",
    "\n",
    "-   [Python library String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations)\n",
    "\n",
    "-   [Old string formatting](http://docs.python.org/tutorial/inputoutput.html#old-string-formatting)\n",
    "\n",
    "-   [Introduction to Fancier Output Formatting, Python tutorial, section 7.1](http://docs.python.org/tutorial/inputoutput.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Changes from Python 2 to Python 3: `print`\n",
    "\n",
    "One (maybe the most obvious) change going from Python 2 to Python 3 is that the `print` command loses its special status. In Python 2, we could print “Hello World” using:\n",
    "\n",
    "```python\n",
    "print \"Hello world\"             # valid in Python 2.x\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Effectively, we call the function `print` with the argument `Hello World`. All other functions in Python are called such that the argument is enclosed in parentheses, i.e."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello World\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello World\")               # valid in Python 3.x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is the new convention *required* in Python 3 (and *allowed* for recent version of Python 2.x.)\n",
    "\n",
    "Everything we have learned about formatting strings using the percentage operator still works the same way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'my pi = 3.141593'"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "a = math.pi\n",
    "\"my pi = %f\" % a           # string formatting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "my pi = 3.141593\n"
     ]
    }
   ],
   "source": [
    "print(\"my pi = %f\" % a)    # valid print in 2.7 and 3.x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Short pi = 3.14, longer pi = 3.141592653590.'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Short pi = %.2f, longer pi = %.12f.\" % (a, a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Short pi = 3.14, longer pi = 3.141592653590.\n"
     ]
    }
   ],
   "source": [
    "print(\"Short pi = %.2f, longer pi = %.12f.\" % (a, a))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Short pi = 3.14, longer pi = 3.141592653590.\n"
     ]
    }
   ],
   "source": [
    "print(\"Short pi = %.2f, longer pi = %.12f.\" % (a, a))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing text to file. This is the first line.\n",
      "And the second line.\n"
     ]
    }
   ],
   "source": [
    "# 1. Write a file\n",
    "out_file = open(\"test.txt\", \"w\")          #'w' stands for Writing\n",
    "out_file.write(\"Writing text to file. This is the first line.\\n\"+\\\n",
    "               \"And the second line.\")\n",
    "out_file.close()                          #close the file\n",
    " \n",
    "# 2. Read a file\n",
    "in_file = open(\"test.txt\", \"r\")           #'r' stands for Reading\n",
    "text = in_file.read()                     #read complete file into \n",
    "                                          #string variable text\n",
    "in_file.close()                           #close the file\n",
    " \n",
    "# 3. Display data\n",
    "print(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reading and writing files\n",
    "-------------------------\n",
    "\n",
    "Here is a program that\n",
    "\n",
    "1.  writes some text to a file with name `test.txt`,\n",
    "\n",
    "2.  and then reads the text again and\n",
    "\n",
    "3.  prints it to the screen.\n",
    "\n",
    "<!-- -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data stored in the file `test.txt` is:\n",
    "\n",
    "```\n",
    "Writing text to file. This is the first line.\n",
    "And the second line.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In more detail, you have opened a file with the `open` command, and assigned this open file object to the variable `out_file`. We have then written data to the file using the `out_file.write` method. Note that in the example above, we have given a string to the `write` method. We can, of course, use all the formatting that we have discussed before—see [formatted printing](#Formatted-printing) and [new style formatting](#New-style-string-formatting). For example, to write this file with name table `table.txt` we can use this Python program It is good practice to `close()` files when we have finished reading and writing. If a Python program is left in a controlled way (i.e. not through a power cut or an unlikely bug deep in the Python language or the operating system) then it will close all open files as soon as the file objects are destroyed. However, closing them actively as soon as possible is better style.\n",
    "\n",
    "### File reading examples\n",
    "\n",
    "We use a file named `myfile.txt` containing the following 3 lines of text for the examples below:\n",
    "\n",
    "    This is the first line.\n",
    "    This is the second line.\n",
    "    This is a third and last line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "f = open('myfile.txt', 'w')\n",
    "f.write('This is the first line.\\n'\n",
    "        'This is the second line.\\n'\n",
    "        'This is a third and last line.')\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### fileobject.read()\n",
    "\n",
    "The `fileobject.read()` method reads the whole file, and returns it as one string (including new line characters)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'This is the first line.\\nThis is the second line.\\nThis is a third and last line.'"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f = open('myfile.txt', 'r')\n",
    "f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### fileobject.readlines()\n",
    "\n",
    "The `fileobject.readlines()` method returns a list of strings, where each element of the list corresponds to one line in the string:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['This is the first line.\\n',\n",
       " 'This is the second line.\\n',\n",
       " 'This is a third and last line.']"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f = open('myfile.txt', 'r')\n",
    "f.readlines()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is often used to iterate over the lines, and to do something with each line. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24 characters\n",
      "25 characters\n",
      "30 characters\n"
     ]
    }
   ],
   "source": [
    "f = open('myfile.txt', 'r')\n",
    "for line in f.readlines():\n",
    "    print(\"%d characters\" % len(line))\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that this will read the complete file into a list of strings when the `readlines()` method is called. This is no problem if we know that the file is small and will fit into the machine’s memory.\n",
    "\n",
    "If so, we can also close the file before we process the data, i.e.:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24 characters\n",
      "25 characters\n",
      "30 characters\n"
     ]
    }
   ],
   "source": [
    "f = open('myfile.txt', 'r')\n",
    "lines = f.readlines()\n",
    "f.close()\n",
    "for line in lines:\n",
    "    print(\"%d characters\" % len(line))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Iterating over lines (file object)\n",
    "\n",
    "There is a neater possibility to read a file line by line which (i) will only read one line at a time (and is thus suitable for large files as well) and (ii) results in more compact code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24 characters\n",
      "25 characters\n",
      "30 characters\n"
     ]
    }
   ],
   "source": [
    "f = open('myfile.txt', 'r')\n",
    "for line in f:\n",
    "    print(\"%d characters\" % len(line))\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, the file handler `f` acts as in iterator and will return the next line in every subsequent iteration of the for-loop until the end of the file is reached (and then the for-loop is terminated).\n",
    "\n",
    "##### Further reading\n",
    "\n",
    "[Methods of File objects, Tutorial, Section 7.2.1](http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
